package sg.edu.nus.iss.billing.gui;

import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import sg.edu.nus.iss.billing.controller.CustomerComplaintController;
import sg.edu.nus.iss.billing.controller.CustomerController;
import sg.edu.nus.iss.billing.entity.Customer;
import sg.edu.nus.iss.billing.entity.CustomerComplaint;
import sg.edu.nus.iss.billing.entity.RecordState;
import sg.edu.nus.iss.billing.exception.ControllerException;
import sg.edu.nus.iss.billing.gui.component.ErrorDialog;
import sg.edu.nus.iss.billing.localization.MessageKeyManager;

public class ViewComplaintPanel extends DefaultFunctionPanel {

  /**
   * 
   */
  private static final long serialVersionUID = 7997321049396705682L;
  CustomerComplaintController customerComplaintController;
  List<CustomerComplaint> complaints;
  JRadioButton[] radioButtons;
  SearchCustomerComplaintsPanel searchPanel;

  void updateButtonPressed(CustomerComplaint complaint) {
    refreshBottomPanel(createEditPanel(complaint));
  }
  
  void saveButtonPressed(CustomerComplaint complaint) {
    try {
      this.customerComplaintController.updateCustomerComplaintStatus(complaint, complaint.getStatus());
    } catch (ControllerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    refreshBottomPanel();
  }

  /**
   * Constructor
   */
  public ViewComplaintPanel() {
    super();
    // initialize member variables
    this.customerComplaintController = new CustomerComplaintController();
    this.searchPanel = null;
    // only show the top panel initially
    super.init("TOPONLY");
  }

  /*
   * Called when the search button is pressed in the search panel
   */
  void searchButtonPressed() {
    // get the customer from the session context
    CustomerController customerController = new CustomerController();
    // get the complaint ID from the search panel
    String complaintID = this.searchPanel.getComplaintID();

    try {
      // first check for the complaint ID
      if ((complaintID != null) && (complaintID.length() != 0)) {
        // get the complaint via the complaint ID
        this.complaints = new ArrayList<CustomerComplaint>();
        this.complaints.add(this.customerComplaintController
            .getCustomerComplaintByReference(complaintID));
        this.refreshBottomPanel();
      } else if (this.searchPanel.getNRIC() != null) {
        Customer customer = customerController.getCustomerByNRIC(this.searchPanel.getNRIC());
        if ((customer != null) && (customer.getActive() == RecordState.ACTIVE)){
        // get the complaint via the customer NRIC
          this.complaints = this.customerComplaintController.getCustomerComplaintByNRIC(customer);
        }
        this.refreshBottomPanel();
      }
    } catch (ControllerException ce) {
      ErrorDialog.showControllerErrorMessageDialog(ce);
    } catch (Exception ex) {
      ErrorDialog.showUnhandledErrorMessageDialog(ex);
    }
  }

  @Override
  public JPanel createTopPanel() {
    // top panel is the search panel
    this.searchPanel = new SearchCustomerComplaintsPanel(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        searchButtonPressed();
      }

    });

    return this.searchPanel;
  }

  public JPanel createEditPanel(CustomerComplaint complaint) {
    JPanel editPanel = new JPanel();
    
    // bottom panel is the list of customer complaints
    editPanel.setLayout(new BorderLayout());

    // create a scroll pane, it should be placed in the center of the
    // bottom panel to take up the entire space of the bottom panel
    JScrollPane scrollPane = new JScrollPane();
    scrollPane
        .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollPane
        .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    editPanel.add(scrollPane, BorderLayout.CENTER);

    // the content panel will contain the actual data
    // which will be one panel per complaint
    JPanel contentPanel = new JPanel();
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 0, 0 };
    gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    contentPanel.setLayout(gridBagLayout);

    // create a containing panel for the content panel and add the content
    // panel in the north of the containing panel to prevent auto-resizing
    JPanel containingPanel = new JPanel(new BorderLayout());
    containingPanel.add(contentPanel, BorderLayout.NORTH);
    
    // set the view port as the containing panel
    scrollPane.setViewportView(containingPanel);

    int i = 0;
    // first add the header
    GridBagHelper.addComponent(contentPanel,
        new ComplaintSummaryDetailsPanel(null, true, null), 0, i++, 0,
        GridBagHelper.INSETS_NONE);
    GridBagHelper.addComponent(contentPanel,
        new ComplaintSummaryDetailsEditPanel(complaint, false, new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            saveButtonPressed((CustomerComplaint)e.getSource());
          }
        }), 0, i++, 0,
        GridBagHelper.INSETS_NONE);

    return editPanel;
  }
  
  @Override
  public JPanel createBottomPanel() {
    // bottom panel is the list of customer complaints
    JPanel bottomPanel = new JPanel();
    bottomPanel.setLayout(new BorderLayout());

    if ((this.complaints == null) || (this.complaints.size() == 0)) {
      // no complaints found, show message to the user
      JOptionPane.showMessageDialog(null, "No complaints found",
          "Search customer complaints", JOptionPane.INFORMATION_MESSAGE);
    } else {
      // create a scroll pane, it should be placed in the center of the
      // bottom panel to take up the entire space of the bottom panel
      JScrollPane scrollPane = new JScrollPane();
      scrollPane
          .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
      scrollPane
          .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
      bottomPanel.add(scrollPane, BorderLayout.CENTER);

      // the content panel will contain the actual data
      // which will be one panel per complaint
      JPanel contentPanel = new JPanel();
      GridBagLayout gridBagLayout = new GridBagLayout();
      gridBagLayout.columnWidths = new int[] { 0, 0 };
      gridBagLayout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
      contentPanel.setLayout(gridBagLayout);

      // create a containing panel for the content panel and add the content
      // panel in the north of the containing panel to prevent auto-resizing
      JPanel containingPanel = new JPanel(new BorderLayout());
      containingPanel.add(contentPanel, BorderLayout.NORTH);
      
      // set the view port as the containing panel
      scrollPane.setViewportView(containingPanel);

      int i = 0;
      // first add the header
      GridBagHelper.addComponent(contentPanel,
          new ComplaintSummaryDetailsPanel(null, true, null), 0, i++, 0,
          GridBagHelper.INSETS_NONE);
      // then add the complaints
      for (CustomerComplaint complaint : this.complaints) {
        GridBagHelper.addComponent(contentPanel,
            new ComplaintSummaryDetailsPanel(complaint, false, new ActionListener() {
              @Override
              public void actionPerformed(ActionEvent e) {
                updateButtonPressed((CustomerComplaint)e.getSource());
              }
            }), 0, i++, 0,
            GridBagHelper.INSETS_NONE);
      }
    }
    
    return bottomPanel;
  }

  @Override
  public JPanel createActionButtonsPanel() {
    // create the button panel
    JPanel buttonPanel = new JPanel(new BorderLayout());

    // set the layout for the content panel
    GridBagLayout gridBagLayout = new GridBagLayout();
    gridBagLayout.columnWidths = new int[] { 0, 100, 0, 0 };
    gridBagLayout.rowHeights = new int[] { 24, 0 };
    gridBagLayout.columnWeights = new double[] { 1.0, 0.0, 1.0,
        Double.MIN_VALUE };
    gridBagLayout.rowWeights = new double[] { 0.0, Double.MIN_VALUE };

    // add the content panel to the north of the button panel to prevent
    // auto resizing
    JPanel contentPanel = new JPanel(gridBagLayout);
    buttonPanel.add(contentPanel, BorderLayout.NORTH);

    // create the view button and add it to the content panel
    JButton btnViewButton = new JButton(
        MessageKeyManager.getMessage("button.save"));
    btnViewButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent arg0) {
        // viewComplaintDialog();
      }
    });
    GridBagHelper.addComponent(contentPanel, btnViewButton, 1, 0, 0,
        GridBagHelper.INSETS_LARGE);

    return buttonPanel;
  }
}